package com.goparry.taskman.inbox;

import java.util.List;

import com.goparry.taskman.R;
import com.goparry.taskman.browse.BrowseFragment.BrowseListeners;
import com.goparry.taskman.repository.Task;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

public class InboxFragment extends ListFragment {
	List<Task> mTasks;
	TaskAdapter mTaskAdapter;
	InboxListeners mInboxListeners;
	
	// Interface that allows the parent InboxActivity to handle list selections
	public interface InboxListeners {
		public void onTaskSelected(Task task);
		public List<Task> onInitialLoad();
	}
	
	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		try {
			mInboxListeners = (InboxListeners) activity;
		} catch (ClassCastException e) {
			throw new ClassCastException(activity.toString() + " must implement OnInitialSelectionListener");
		}
	}
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.inboxfragment, container, false);
    }
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        // Get the Task List from the parent InboxActivity
        mTasks = mInboxListeners.onInitialLoad();
        
        // Create a new TaskAdapter and apply it to the ListView
        mTaskAdapter = new TaskAdapter(getActivity().getApplicationContext(), R.layout.inbox_row, R.id.name, mTasks);
        setListAdapter(mTaskAdapter);
	}
	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {
		// This handles a selection of a task in the InBox ListView.
		// The work is actually done in the parent activity.
		Task task = mTasks.get(position);
		mInboxListeners.onTaskSelected(task);
	}

}
